from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from . serializers import CitySerializer
from xj_users.models import City
from rest_framework.viewsets import ModelViewSet
from rest_framework.decorators import action


# Create your views here.
# 热门城市返回  get
class HostCityView(APIView):

    # 查询集 并序列化
    def get(self, request):

        # 过滤得到热门的城市
        hostcitys = City.objects.filter(ishot=1)

        # 将对象序列化返回
        serializer = CitySerializer(instance=hostcitys, many=True)
        return Response(serializer.data)


# ================================================

from xj_users.models import Enterprise
from .serializers import EnterpriseSerializer,EnterpriseSerializerSimple



# 企业视图集
class EnterpriseViewSet(ModelViewSet):
    queryset = Enterprise.objects.all()


    def get_serializer_class(self):

        # 对企业界面的切换操作，　返回列表详情
        if self.action == "retrieve":

            # 企业详情返回
            return EnterpriseSerializer
        else:

            # 简单返回
            return EnterpriseSerializerSimple






    # 企业方访问量统计  put
    def qyvistcount(self, request, pk):

        # 根据ｐｋ接收到企业对象
        qy = self.get_object()
        qy.visits += 1
        qy.save()
        return Response({'success': True, 'message': '更新成功'})


    # 4个热门企业返回   get
    def hotest_enterprise(self, request):

        # 得到所有的企业对象，　按照访问量降序
        hostest_enterprises = self.get_queryset().order_by("-visits")[0:4]
        serializer = self.get_serializer(instance=hostest_enterprises, many=True)
        return Response(serializer.data)


    # 收藏企业post  　　　企业myslq表增加user字段
    def user_shoucangQY(self, request, pk):

        # 得到请求用户对象　
        user = request.user

        # 判断是否登录
        if user and user.is_authenticated:

            # 根据pk接受到企业对象
            qy = self.get_object()

            # 企业对象有一个users字段（表示收藏者)
            qy.users.add(user)
            qy.save()
            return Response({'success': True,
                             'message': '收藏成功'})
        else:

            # 为登录返回错误
            return Response({'success': False,
                             'message': '未登录'}, status=400)


    # 取消企业收藏 post
    def user_deleteQY(self, request, pk):

        # 得到请求用户
        user = request.user
        if user and user.is_authenticated:

            # 得到企业对象
            qy = self.get_object()
            qy.users.remove()
            qy.save()

            return Response({'success': True,
                             'message': '取消成功'})

        else:
            # 未登录返回错误
            return Response({'success': False,
                             'message': '未登录'}, status=400)





# 企业详情视图
class EnterpriseDetailView(APIView):


    def get(self, request, pk):

        qy = Enterprise.objects.get(pk=pk)

       #　注意这里所用的序列化器
        serializer = EnterpriseSerializer(qy)

        return Response(serializer.data)










# ============================================================

from xj_users.models import Recruit
from .serializers import RecruitSerializer, RecruitSerializerSimple




# 职位视图集
class RecruitViewSet(ModelViewSet):
    queryset = Recruit.objects.filter(state="1").order_by("-createtime")

    def get_serializer_class(self):
        if self.action == 'retrieve':

            # 最高层嵌套 用于职位详情
            return RecruitSerializer
        else:
            return RecruitSerializerSimple


    # 推荐的四个职位
    def tj_job(self, request):
        recruits = self.get_queryset()[0:4]
        serializer = self.get_serializer(instance=recruits, many=True)
        return Response(serializer.data)


    # 最新的四个职位
    def newest_job(self, request):
        recruits = self.get_queryset()[0:4]
        serializer = self.get_serializer(instance=recruits, many=True)
        return Response(serializer.data)



    # 搜索职位
    def searchjob(self, request):

        # 接收数据 （城市名字， 字段）
        cityname = request.data.get('cityname')
        keyword = request.data.get('keyword')
        jobs = self.get_queryset()

        # 建立返回列表
        find_jobs = []
        # 未输入城市，未输入关键字  查所有职位
        if not cityname and not keyword:
            find_jobs = jobs
        # 输入城市，但是没有关键字    查该城市的所有职位
        elif cityname and not keyword:
            for job in jobs:
                if job.city == cityname:
                    find_jobs.append(job)

        #  未输入城市  有关键词  查包含关键词的所有职位
        elif not cityname and keyword:
            for job in jobs:

                # find 函数，找到返回，没找到返回-1
                # str.find(str, beg=0, end=len(string))
                if job.jobname.lower().find(keyword.lower()) != -1:
                    find_jobs.append(job)
        # 既有城市 又有关键词  查询指定职位
        else:
            for job in jobs:
                if job.city == cityname and job.jobname.lower().find(keyword.lower()) != -1:
                    find_jobs.append(job)

                # else:
                #     raise Exception('未查询到相关职位')


        # 创建序列化对象
        serializer = self.get_serializer(instance=find_jobs, many=True)
        return Response(serializer.data)


    # 职位访问次数统计
    def job_vistcount(self, request, pk):
        job = self.get_object()
        job.visits += 1
        job.save()
        return Response({'success': True, 'message': '更新成功'})


    # 收藏职位
    def user_celectingJob(self, request, pk):

        user = request.user

        if user and user.is_authenticated:
            job = self.get_object()
            job.users.add(user)
            job.save()
            return Response({'success': True,
                             'message': '收藏成功'})
        else:
            return Response({'success': False,
                             'message': '未登录'}, status=400)


    def usr_deleteJob(self, request, pk):

        user = request.user

        if user and user.is_authenticated:
            job = self.get_object()
            job.users.remove(user)
            job.save()
            return Response({'success': True,
                             'message': '已取消'})

        else:
            return Response({'success': False,
                             'message': '请登录后重试'})




# 职位详情视图集
class Job_ViewSet(APIView):

    def get(self, request, pk):
        job = Recruit.objects.get(pk=pk)

        # 　注意这里所用的序列化器
        serializer = RecruitSerializer(job)

        return Response(serializer.data)












